<?php
class categoryEditAction extends sfActions
{
	public function execute($request)
	{
		$this->cms_category_id = $request->getParameter('cms_category_id');
		if ($this->cms_category_id) {
			$this->cms_category = Doctrine_Core::getTable('VTNSCmsCategory')->find($this->cms_category_id);
            if(isset($this->cms_category))
			     $this->cms_category_form = new AdminCmsCategoryForm($this->cms_category);
		}
        else {
            $this->cms_category_form = new AdminCmsCategoryForm();
        }

		if ($request->hasParameter('cms_category')) {
			$form = $request->getParameter('cms_category');
			$this->status = $this->updateCmsCategoryFromRequest($this->cms_category, $form);
			if ($this->status) {
				$this->cms_category->save();
				$this->forward('cms', 'categoryList');
			} else
				return SfView::SUCCESS;
		} else
			return SfView::SUCCESS;
	}

	private function updateCmsCategoryFromRequest(&$cms_category, $form)
	{
		$cms_category->name = $form['name'];
		$cms_category->name_vi = $form['name_vi'];
		if ($cms_category->name == '')
			$cms_category->name = $cms_category->name_vi;
		else if ($cms_category->name_vi == '')
			$cms_category->name_vi = $cms_category->name;

		if ($form['alias'])
			$cms_category->alias = $form['alias'];
		if (isset($form['parent_id']))
			$cms_category->parent_id = $form['parent_id'];
		if (isset($form['cms_type']))
			$cms_category->cms_type = $form['cms_type'];
		if (isset($form['template']))
			$cms_category->template = $form['template'];
		if (isset($form['position']))
			$cms_category->position = $form['position'];
        $level = 0;
		if ($form['parent_id'] != 0)
		{
			$parent = Doctrine_Core::getTable('VTNSCmsCategory')->find($form['parent_id']);
			$level = $parent->level + 1;
		}
		$cms_category->level = $level;
		$cms_category->updated_at = date(DATE_ISO8601);
		return true;
	}
}
?>